﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AteneoLibri.DomainObject;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibri.BackEnd
{
    public partial class ManageUsers : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            // Reuperare gli users
            if (!Page.IsPostBack)
            {
                List<AteneoLibriBusinessLogic.Entities.User> users = new List<User>();
                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    users = service.getUsers();

                    //List<UserStatusInfo> usersList = new List<UserStatusInfo>();

                    //foreach (var item in users)
                    //{
                    //    UserStatusInfo uInfo = new UserStatusInfo();

                    //    uInfo.IdUser = item.IdUser;
                    //    uInfo.Name = item.Name;
                    //    uInfo.Surname = item.Surname;
                    //    uInfo.Email = item.Email;
                    //    uInfo.RegistrationData = item.RegistrationData;
                    //    uInfo.ImageStatus = LoadImageStatus(item.IsSuspended);

                    //    usersList.Add(uInfo);
                    //}                                     

                }

                lblNumberOfUsers.Text = users.Count.ToString();

                Session["BACK_END_USER_LIST"] = users;
                LoadUsers();   
            }
        }

        private void LoadUsers()
        {
            List<User> users = Session["BACK_END_USER_LIST"] as List<User>;

            gvUsers.DataSource = users.OrderByDescending(x => x.RegistrationData).ThenBy(x => x.Surname).ThenBy(x => x.Name).ToList();
            gvUsers.DataBind();
        }

        protected void btnSuspend_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton button = sender as ImageButton;
            string IdUser = button.CommandArgument;

            // recuperare l'utente ed aggiornare lo stato
            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                Guid userId = new Guid(IdUser);

                AteneoLibriBusinessLogic.Entities.User user = service.getUserById(userId);

                if (!user.IsSuspended.HasValue)
                {
                    user.IsSuspended = true;
                }
                else
                {
                    if (!user.IsSuspended.Value) // se non è sospeso lo sospendo e viceversa
                    {
                        user.IsSuspended = true;
                    }
                    else
                    {
                        user.IsSuspended = false;
                    }
                }

                bool result = service.updateUser(user);
                if (result)
                {
                    Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
                    mailSender.SendMail(user.Email, "Sospensione temporanea", "I servizi di AteneoLibri.it non sono più disponibili per il tuo account.", true);
                }

            }
        }

        protected string LoadImageStatus(bool? isSuspended)
        {
            string path = string.Empty;

            if (isSuspended.HasValue)
            {
                if (isSuspended.Value)
                {
                    path = "../Images/ico_red.png";
                }
                else
                {
                    path = "../Images/ico_green.png";
                }
            }
            else
            {
                path = "../Images/ico_yellow.png";
            }
            

            return path;
        }

        protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e)
        {
            //ViewState["sortexp"] = e.SortExpression;
            //gvUsers.DataSource = usersList;
            //gvUsers.DataBind();

            try
            {                
                //gvUsers.Sort(e.SortExpression,  e.SortDirection);
                //gvUsers.DataSource = view;
                //gvUsers.PageIndex = 0;
                //gvUsers.DataBind();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
            
        }

        protected string SetSortDirection(string column)
        {
            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

        protected void gvUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvUsers.PageIndex = e.NewPageIndex;
            LoadUsers();
        }
    }
}